package com.example.traning.mall.framework.security.core.handler;

import com.example.traning.mall.framework.common.ex.GlobalErrorCodeConstants;
import com.example.traning.mall.framework.common.pojo.R;
import com.example.traning.mall.framework.common.util.servlet.ServletUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

import static com.example.traning.mall.framework.common.ex.GlobalErrorCodeConstants.UNAUTHORIZED;


/**
 * 访问一个需要认证的 URL 资源，但是此时自己尚未认证（登录）的情况下，返回 {@link GlobalErrorCodeConstants#UNAUTHORIZED} 错误码，从而使前端重定向到登录页
 *
 * @author lei yu
 * @since 2024/10/15
 */
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.warn("[commence][访问 URL({}) 时，没有登录]", request.getRequestURI(), e);
        // 返回 403
        ServletUtils.writeJson(response, R.error(UNAUTHORIZED));
    }
}
